#include "PostData.h"
#include <stdlib.h>
//

inline PostData::HeadersType PostData::HT()
{
	HeadersType headers_ = {
		QString("\r\nContent-Disposition: "),
		QString("form-data; name=\""),
		QString("\"\r\n\r\n"),
		QString("\"; filename=\""),
		QString("\"\r\nContent-Transfer-Encoding: binary\r\n\r\n"),
		QString("\"\r\nContent-Type: %1\r\n\r\n"),
		QString("\r\n"),
	};
	return headers_;
}

inline QString PostData::textPostData() { return "--%1" + Headers.ContentDisposition + Headers.FieldName + "%2" + Headers.FieldValue + "%3" + Headers.EndField; }
inline QString PostData::binPostData() { return "--%1" + Headers.ContentDisposition + Headers.FieldName + "%2" + Headers.FileName + "%3" + Headers.ContentEncoding; }
inline QString PostData::binPostDataContentType() { return "--%1" + Headers.ContentDisposition + Headers.FieldName+"%2" + Headers.FileName + "%3" + "%4"; }

PostData::PostData(int boundaryLength)
	: QByteArray(),
	boundary(genBoundary(boundaryLength)),
	finalized(false),
	Headers(HT())
{ }

PostData::PostData( QString boundary_ )
	: QByteArray(),
	boundary(boundary_),
	finalized(false),
	Headers(HT())
{ }


QString PostData::genBoundary(int length)
{
	if (length <=0 ) return QString::null;
	if (length > 70)
		length = 70;
	QString str; //str.setLength( length );
	while (length--)
	{
		int r=rand() % 62;
		r+=48;
		if (r>57) r+=7;
		if (r>90) r+=6;
		str += char(r);
	// so what if I work backwards?
	}
	return str;
}

void PostData::appendTextField(const QString &field, const int value)
{ appendTextField(field, QString::number(value)); }

void PostData::appendTextField(const QString &field, const QString &value)
{
	if ( !finalized )
	{ this->append(textPostData().arg(boundary,field,value)); }
}


void PostData::appendBinaryField(const QString &field, const QString &fileName, const QByteArray &data)
{
	if ( !finalized )
	{
		qDebug() << binPostData().arg(boundary,field,fileName);
		this->append(binPostData().arg(boundary,field,fileName));
		this->append(data);
		this->append(Headers.EndField);
	}
}
void PostData::appendBinaryField(const QString &field, const QString &fileName, const QString &ContentType, const QByteArray &data)
{
	if ( !finalized )
	{
		qDebug() << binPostDataContentType().arg(boundary,field,fileName, Headers.ContentType.arg(ContentType));
		this->append( binPostDataContentType().arg(boundary,field,fileName, Headers.ContentType.arg(ContentType)) );
		this->append(data);
		this->append(Headers.EndField);
	}
}


void PostData::finalize()
{
	if ( !finalized )
	{
		this->append("--"+ boundary +"--\r\n");
		finalized = true;
	}
}


